import redis
import requests
import json
import httpfpt.core.load_conf as load
import os


class PreLogin:
    phone_number = "15754365508"

    def __init__(self):
        self.host = '39.105.231.186'
        self.db = 3
        self.phone_number = "13502193414"

        # 线上库 谨慎操作
        # self.host = '172.21.230.146'

    def read_token_xyapp(self, phone_number):
        return "123456"
        r = redis.StrictRedis(host=self.host, port=6379, db=self.db, password='HappyRdb!%',
                              decode_responses=True)
        try:
            r.ping()
            print("Connected to Redis!")
        except redis.ConnectionError:
            print("Failed to connect to Redis.")
            return "null"
        key = 'xyapp-login-verification-code-%s' % phone_number
        # xyapp-login-verification-code-13502193414

        try:
            value = r.get(key)
            print("Value for 'mykey':", value)
            value_dict = json.loads(value)
            verification_code = value_dict.get('verificationCode')
            print("Value for 'verification_code':", verification_code)
            return verification_code
        except:
            print("获取redis value异常")
            return "null"

    def send_sms_code(self, phone_number):
        data = {
            "typeId": 20,
            "mobileNumber": phone_number
        }
        headers = {
            "Content-Type": "application/json"
        }
        response = requests.post('http://csxyapi.beijingliuli.top/xinyu/tokens/sms-verification-codes', json=data,
                                 headers=headers)
        # 处理响应
        if response.status_code == 200:
            data = response.json()
            print(data)
            try:
                code = self.read_token_xyapp(phone_number)
                return code
            except:
                return "null"
        else:
            print('请求失败:', response.status_code)
            return "null"

    def requst_access_token(self, code, phone_number):
        data = {
            "smsVerificationCode": code,
            "mobileNumber": phone_number
        }
        headers = {
            "Content-Type": "application/json"
        }
        response = requests.post('http://csxyapi.beijingliuli.top/xinyu/tokens', json=data,
                                 headers=headers)
        if response.status_code == 200:
            data = response.json()
            print(data)
            print(data['data']['accessToken'])
            return data['data']['accessToken']
        else:
            print('请求失败:', response.status_code)
            return "null"

    def get_token(self):
        # 每次自动化之前，执行登陆操作
        token = self.run()
        return token

    def run(self):
        verificationCode = self.read_token_xyapp(self.phone_number)
        # 有未过期的，直接请求token
        if verificationCode != "null":
            token = self.requst_access_token(verificationCode, self.phone_number)
            return token
        else:
            # token已过期，重新发送验证码请求
            verificationCode = self.send_sms_code(self.phone_number)
            if verificationCode != "null":
                token = self.requst_access_token(verificationCode, self.phone_number)
                return token
            else:
                print('获取或重写access_token失败，后续请求可能无权限！！！！！！！')
                return "null"

    def get_token_bi(self):
        script_directory = os.path.dirname(os.path.abspath(__file__))
        print(script_directory)
        config = load.load_yaml(script_directory + "/../core/project_info.yaml")
        data = {
            "phone": config['bi']['phone'],
            "password": config['bi']['password']
        }
        url = config['bi']['host']
        response = requests.post(url + '/admin/account/login', data=data)
        if response.status_code == 200:
            print(response.json())
            token = response.headers['Token']
            print(token.split(',')[1])
            return token.split(',')[1].strip()
        else:
            print('请求失败:', response.status_code)
            return "null"


if __name__ == '__main__':
    pre_login = PreLogin()
    pre_login.get_token()
